package com.breaktian.demoapp.ui.jetpack;

import android.arch.lifecycle.Observer;
import android.arch.lifecycle.ViewModelProvider;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.View;
import android.widget.TextView;

import com.breaktian.assemble.livedatabus.LiveDataBus;
import com.breaktian.assemble.utils.ToastUtil;
import com.breaktian.demoapp.R;
import com.breaktian.demoapp.ui.base.Base2Activity;
import com.breaktian.demoapp.ui.jetpack.viewmodel.TestViewModel;
import com.breaktian.network.api.finance.ApiResult;

public class JetpackActivity extends Base2Activity<TestViewModel> {

    private TextView textView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_jetpack);
        showToolbar("JetPack");



        textView = (TextView)findViewById(R.id.textView);
        textView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ToastUtil.show("click");
//                getViewModel().getBean().setValue(new TestViewModel.Bean("11","22"));
                getViewModel().loadBean();

            }
        });

        LiveDataBus.getDefault().channel("test",String.class).subscribe(this, new Observer<String>() {
            @Override
            public void onChanged(@Nullable String s) {
                textView.setText(s);
            }
        });

        findViewById(R.id.button).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                LiveDataBus.getDefault().channel("test").send("我是从jetpack过来的");
                startActivity(new Intent(JetpackActivity.this,JetPack2Activity.class));
            }
        });


        subscribe();

    }

    @Override
    protected TestViewModel getViewModel() {
        ViewModelProvider.AndroidViewModelFactory factory = ViewModelProvider.AndroidViewModelFactory.getInstance(getApplication());
        ViewModelProvider provider = new ViewModelProvider(this,factory);
        return provider.get(TestViewModel.class);
    }


    /**
     * 订阅
     * */
    private void subscribe() {
        getViewModel().getBean().observe(this, new Observer<TestViewModel.Bean>() {
            @Override
            public void onChanged(@Nullable TestViewModel.Bean bean) {
                ToastUtil.show("changed");
                textView.setText(bean.desc+"|"+bean.title);
            }

        });
        getViewModel().getError().observe(this, new Observer<ApiResult.ApiError>() {
            @Override
            public void onChanged(@Nullable ApiResult.ApiError apiError) {
                ToastUtil.show("apiError");
                textView.setText(apiError.message);
            }
        });
    }

}
